package model

import (
	config "gitee.com/lanshiren/miniprogram/app/conf"
	"time"
)

const (
	RegistrationDone = iota
	RegistrationCancel
)

type RegistrationActivityParam struct {
	ActivityID uint `json:"activity_id"`
}

type RegistrationDO struct {
	ID         uint      `gorm:"primary_key"`
	UpdatedAt  time.Time `gorm:"updated_at"`
	CreatedAt  time.Time `gorm:"created_at"`
	UserID     uint      `gorm:"user_id"`
	ActivityID uint      `gorm:"activity_id"`
	CancelTime time.Time `gorm:"cancel_time"`
	Status     int       `gorm:"status"`
}

type RegistrationUserVO struct {
	RegistrationDO
	UserVO
}

func (RegistrationDO) TableName() string {
	return "registration"
}

func CreateRegistration(rs *RegistrationDO) error {
	db := config.GetDB()
	return db.Save(rs).Error
}

func QueryAndUpdateRegistration(userId, acId, status uint) error {
	db := config.GetDB()
	res := RegistrationDO{}
	err := db.Where("user_id = ? AND activity_id = ?", userId, acId).First(&res).Error
	if err != nil {
		return err
	} else {
		err := db.Model(&res).Updates(
			map[string]interface{}{
				"status": status,
			}).Error
		if err != nil {
			return err
		}
	}
	return err
}

func UpdateRegistrationDO(rs *RegistrationDO) error {
	db := config.GetDB()
	registrations := []*RegistrationDO{}
	err := db.Table("registration").Where("user_id = ? AND activity_id = ?", rs.UserID, rs.ActivityID).
		Scan(&registrations).Error
	if err != nil {
		return err
	}
	for _, registration := range registrations {
		err = db.Table("registration").Model(&registration).Updates(
			RegistrationDO{
				ID:         registration.ID,
				Status:     rs.Status,
				CancelTime: time.Now(),
			}).Error
		if err != nil {
			return err
		}
	}
	return nil
}

func GetRegistrationListByAcID(acId uint) (rss []*RegistrationDO, err error) {
	db := config.GetDB()
	err = db.Table("registration").Where("activity_id = ?  AND status = ?", acId, RegistrationDone).Scan(&rss).Error
	return
}

func GetRegistrationByUIDAndAcID(userId, acId uint) (rss []*RegistrationDO, err error) {
	db := config.GetDB()
	err = db.Table("registration").Where("user_id = ? AND activity_id = ?", userId, acId).
		Scan(&rss).Error
	return
}

// select * from registration join users on registration.user_id
// = users.id where activity_id = 32;
func GetRegistrationWithUsers(id uint) (rss []*RegistrationUserVO, err error) {
	db := config.GetDB()
	err = db.Table("registration").Select("*").
		Joins("JOIN users ON registration.user_id = users.id").
		Where("activity_id = ? and registration.status = ?", id, RegistrationDone).
		Scan(&rss).
		Error
	return
}

func GetRegistrationOnlineByUIDAndAcID(userId, acId uint) (rss []*RegistrationDO, err error) {
	db := config.GetDB()
	err = db.Table("registration").Where("user_id = ? AND activity_id = ? AND status = ?", userId, acId, RegistrationDone).
		Scan(&rss).Error
	return
}
